package com.rw.interceptor;

import com.rw.controller.LoginController;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginController loginController;
    /**
     *
     * preHandle表示的在第一请求进入controller方法之前进行操作
     * 返回布尔值：false:表示的是请求不满足访问controller方法的条件
     *          true:表示的满足访问controller方法，直接放行
     * @param request 前端访问的HttpServletRequest对象，包含了前端访问的所有信息（请求头，参数等）
     * @param response  dispatchServlet注入进来的HttpServletResponse，他可以包含所有的相应信息
     * @param handler 表示的是HandlerMethod实例化属性，由dispatchServlet来调用
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor.preHandle-执行了");
        //判断 Object handler 是否和HandlerMethod 是同一个类
//        if(handler instanceof HandlerMethod){
//            HandlerMethod handlerMethod = (HandlerMethod) handler;
//            System.out.println( handlerMethod.getMethodParameters()[0].getParameterName());;
//            handlerMethod.getMethod().invoke(loginController,null);
//            System.out.println("MyInterceptor通过反射执行了controller方法");
//        }

//        response.setContentType("text/html;charset=utf-8");
//        response.getWriter().println("MyInterceptor.preHandle-执行了");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        final Object str = modelAndView.getModel().get("str");
        System.out.println(str);
        modelAndView.getModel().put("str","postHandle设置的值");
        System.out.println("MyInterceptor.postHandle-准备执行了");
    }

    /**
     * 一般用来处理异常或者关闭资源
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
       if (ex != null){
           System.out.println(ex.getMessage());
       }

        System.out.println("MyInterceptor.afterCompletion--执行了");
    }
}
